package io.gitee.macxiang.entity;

import java.lang.reflect.Field;

import io.gitee.macxiang.utils.Datas;
import io.gitee.macxiang.utils.SQL;
import io.gitee.macxiang.utils.Times;
import lombok.Data;

@Data
public class SqlFieldMap {
  final public String sqlName;
  final public String inValue;
  final public String upValue;
  final public Field field;
  final public boolean exist;
  final public boolean select;
  final public String sqlNameSimple;
  public boolean isString = true;

  public SqlFieldMap(String sqlName, String inValue, String upValue, Field field, boolean exist, boolean select) {
    this.sqlName = sqlName;
    this.inValue = inValue;
    this.upValue = upValue;
    this.field = field;
    this.exist = exist;
    this.select = select;
    sqlNameSimple = sqlName.trim().replaceAll("^`*|`*$", "").trim();
  }

  public String getValue(Object entity, boolean insert) {
    try {
      if (exist) {
        Object o = this.field.get(entity);
        if (o == null) {
          if (!insert && this.upValue == null) {
            return null;
          }
          String v = insert ? this.inValue : this.upValue;
          switch (v) {
            case "TIMESTAMP":
              o = Times.time();
              break;
            case "TIME_ISO8601":
              o = Times.timeISO8601();
              break;
            case "LONG":
              o = Datas.sGetId();
              break;
            case "STR32":
              o = Datas.sGetId32();
              break;
            case "STR36":
              o = Datas.sGetId36();
              break;
            case "STR40":
              o = Datas.sGetId40();
              break;

            default:
              break;
          }
          o = o == null ? v : SQL.safeJSON(o);
          try {
            this.field.set(entity, Datas.parseJavaObject(o.toString(), this.field.getType()));
          } catch (Exception e) {
          }
        } else {
          o = SQL.safeJSON(o);
        }
        return o.toString();
      } else {
        return null;
      }
    } catch (Exception e) {
    }
    return "DEFAULT";
  }
}
